#This file is part of Cute-Client.
#
#Cute-Client is free software: you can redistribute it and/or modify
#it under the terms of the GNU Lesser General Public License as published by
#the Free Software Foundation, either version 3 of the License, or
#(at your option) any later version.
#
#Cute-Client is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#GNU Lesser General Public License for more details.
#
#You should have received a copy of the GNU Lesser General Public License
#along with Cute-Client.  If not, see <http://www.gnu.org/licenses/>.

from cssession import CSSession
import socket

class CSClient(object):
    '''
    CSClient object is the representation of a connecion with a cute-server.
    It allows to open or join sessions on the server.
    @author Aurelien Deharbe
    @version 1.0
    '''

    def __init__(self, host, port):
        '''
        Construct and connect a client
        @param host cute-server host
        @param port cute-server port
        @raise QSException If there is connexion problem
        '''
        self._serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self._serversocket.connect((host, port))
    
    def newSession(self, sessid):
        '''
        Open a new session on the cute-server
        @param sessid The unique id of the session
        @return The session object
        @throws CSException If there is connexion problem,
        or if sessid is already used attribute by the server
        '''
        return self.__accessSession("QSSessionNew(" + sessid + ")\n")
    
    def joinSession(self, sessid):
        '''
        Join an existing session on the cute-server
        @param sessid The unique id of the session
        @return The session object
        @throws CSException If there is connexion problem,
        or if sessid is not an existing session id on the server
        ''' 
        return self.__accessSession("QSSessionJoin(" + sessid + ")\n")
    
    def __accessSession(self, cmd):
        '''
        Effectively connect to a cute-server session
        @param cmd The command required to join or create a session
        @return The session object
        @throws CSException If there is a connexion problem
        '''
        if not self._serversocket:
            return None
        self._serversocket.send(cmd)
        self._serversocket.recv(256)
        session = CSSession()
        sessport = session.getPort()
        self._serversocket.send("QSSessionPort(" + str(sessport) + ")\n")
        self._serversocket.recv(256)
        session.accept()
        return session
